package surreal.triviamaster.gui;

import java.util.Random;

import surreal.triviamaster.R;
import surreal.triviamaster.beans.Answer;
import surreal.triviamaster.beans.Question;
import surreal.triviamaster.database.LocalCache;
import surreal.triviamaster.utilities.TriviaMasterApplication;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Game extends ListActivity{
	private Question question;
	private LocalCache db;
	private int curQuizIndex;
	private String[] aList=null;
	
	@Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    //forcing orientation
	    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	    
	    Log.d("GAME" , "on create");
	    
	    //get db, increase quiz index, get question
	    db = ((TriviaMasterApplication) getApplication()).getLocalCache();
	    
	    if(db.getUserQuizLength()==0) {
	    	//if the quiz has zero items in it go back to the home page
	    	Toast.makeText(Game.this, "Please choose another category", 10000);
	    	Intent intent = new Intent(Game.this, TriviaMasterActivity.class);
	      	startActivity(intent);
	    } else if(db.getUserQuizIndex()==db.getUserQuizLength()) {
		    //check to see if the quiz is over, if it is, go to the results activity
	    	
	    	//display results of quiz
			Intent intent = new Intent(Game.this, Results.class);
	      	startActivity(intent);
	    } else {
	    	
		    setContentView(R.layout.game);
			curQuizIndex = db.incrementUserQuizIndex(); 
		    question = db.getCurrentQuizQuestion();
		    
		    //setting the current points 		
		    TextView currentPoints=((TextView) findViewById(R.id.currentPoints));
		    TextView totalPoints=((TextView) findViewById(R.id.totalPoints));
			currentPoints.setText("Cur: "+TriviaMasterApplication.POINT_VALUE_FULL);
			totalPoints.setText("T: "+db.getCurrentQuizScore());
			
		    //Display question in GUI
		    if(db.getCurrentQuizCategory()!=0) {
		    	((TextView) findViewById(R.id.quizIndex)).setText(db.getCurrentQuizCategoryString() + " " +curQuizIndex + " of " + db.getUserQuizLength());
		    } else {
		    	((TextView) findViewById(R.id.quizIndex)).setText(curQuizIndex + " of " + db.getUserQuizLength());
		    }
		    ((TextView) findViewById(R.id.question)).setText(question.getQuestion());
		    ((TextView) findViewById(R.id.hintTextView)).setText("");
		    if(question.getHint().equals("")) {
		    	//if there are no fAs
		    	if(db.getCurrentQuizQuestion().getfAs().length==0) {
		    		((Button) findViewById(R.id.hintButton)).setEnabled(false);
		    	//else there are fAs
		    	} else {
		    		((Button) findViewById(R.id.hintButton)).setText("Multiple Choice");
		    	}
		    }
		   
		    //Flag Question button
		    Button flagQuestion = (Button) findViewById(R.id.flagQuestion);
		    flagQuestion.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	Intent intent = new Intent(Game.this, FlagQuestion.class);
		  	      	startActivity(intent);
	            }
	        });
		    
		    //Home button
		    Button home = (Button) findViewById(R.id.home);
		    home.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	Intent intent = new Intent(Game.this, TriviaMasterActivity.class);
		  	      	startActivity(intent);
	            }
	        });
		    
		  //Hint button
		    Button hint = (Button) findViewById(R.id.hintButton);
		    hint.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	handleHint();
	            }

	        });
		    
		    //submit button
		    Button submit = (Button) findViewById(R.id.submit);
		    submit.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	
	            	//getting the answer given by the user
	            	String answer = ((EditText)findViewById(R.id.answer)).getText().toString(); 
	            	boolean guess = question.guess(answer);
	            	Log.d("Game", "Distance match: " +guess);
	            	if(guess) {
	            		//alter the local cache
	            		
	            		db.setCurrentQuizQuestion(answer, true);
	        			Intent intent = new Intent(Game.this, Correct.class);
	        			boolean isQuizOver = db.getUserQuizIndex()==db.getUserQuizLength();
	        			intent.putExtra("isQuizOver", isQuizOver);
		  	      		startActivity(intent);
	            		
	            	} else {
	            		db.setCurrentQuizQuestion(answer, false);
	        			Intent intent = new Intent(Game.this, Incorrect.class);
	        			boolean isQuizOver = db.getUserQuizIndex()==db.getUserQuizLength();
	        			intent.putExtra("yourAnswer", answer);
	        			intent.putExtra("isQuizOver", isQuizOver);
		  	      		startActivity(intent);
	            		
	            	}
	            }
	        });
		    
	    }
	}
	
	private void handleHint() {
		String[] butLabel = new String[]{"Hint", "Multiple Choice"};
		
		//getting references
		TextView hintTextView =((TextView) findViewById(R.id.hintTextView));
		TextView currentPoints=((TextView) findViewById(R.id.currentPoints));
		Button hintButton = ((Button) findViewById(R.id.hintButton));
				
		//if the hint is clicked
		if(hintButton.getText().equals(butLabel[0])) {
			//setting the current point label		
			currentPoints.setText("Cur: "+TriviaMasterApplication.POINT_VALUE_HINT);
	    	hintTextView.setText("Hint: " + question.getHint());
	    	db.setQuestionHint(1, question.getId());
	    	//if there are no fAs
	    	if(db.getCurrentQuizQuestion().getfAs().length==0) {
	    		hintButton.setEnabled(false);
	    	//else there are fAs
	    	} else {
	    		hintButton.setText(butLabel[1]);
	    	}
	    //if mult choice is clicked
		} else {
			//setting the current point label		
			currentPoints.setText("Cur: "+TriviaMasterApplication.POINT_VALUE_MC);
			
			//force the keyboard to close
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(hintTextView.getWindowToken(),0); 
			//getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
			//disable the multiple choice button
			hintButton.setEnabled(false);
			db.setQuestionMC(1, question.getId());
			Answer[] fAs = question.getfAs();
			aList=new String[fAs.length+1];
			
			for(int i=0; i<fAs.length;i++) {
				aList[i]=fAs[i].getAnswer();
			}
			
			//getting a random acceptable answer and placing it at the end of the list
			Random generator = new Random();
			int r = generator.nextInt(question.getaAs().length);
			
			aList[fAs.length] = question.getaAs()[r].getAnswer();
			
			//randomly shuffling the list
			for(int i=0;i<aList.length;i++) {
				r = generator.nextInt(aList.length);
				aList=swap(aList, i, r);
			}
			
			setListAdapter(new ArrayAdapter<String>(this, R.layout.generic_list_item, aList));

	    	ListView lv = getListView();
	    	lv.setTextFilterEnabled(true);
 
	    	// When clicked, open that activity
	    	lv.setOnItemClickListener(new OnItemClickListener() {
	    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	    			((TextView) findViewById(R.id.answer)).setText(aList[position]);
	    		}
	    	});
		}
  
	}
	/**
	 * Swaps two items in a string list
	 * @param aList The list itself
	 * @param i The first index
	 * @param r The second index
	 * @return The new swapped list
	 */
	private String[] swap(String[] aList, int i, int r) {
		String tmp = aList[r];
		aList[r] = aList[i];
		aList[i] = tmp;
		return aList;
	}
	
	@Override
	public void onBackPressed() {
	   return;
	}
}
